package arina.university.dao.impl.memory;

import arina.university.dao.UniversityDAO;
import arina.university.errorhandling.DAOException;
import arina.university.model.University;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: user
 * Date: 26.11.13
 * Time: 9:39
 * To change this template use File | Settings | File Templates.
 */
public class MemoryUniversityDAO implements UniversityDAO {
    private Map<String, University> universities = new HashMap<String, University>();
    static private MemoryUniversityDAO memoryUniversityDAO;

    private MemoryUniversityDAO() {
    }

    public static MemoryUniversityDAO getInstance() {
        if (memoryUniversityDAO == null) {
            memoryUniversityDAO = new MemoryUniversityDAO();
        }
        return memoryUniversityDAO;

    }

    public boolean checkExistence(String name) {
        if (universities.containsKey(name)) {
            return true;
        }
        else return false;
    }

    @Override
    public University create(String name) throws DAOException {
        if(checkExistence(name)){
            throw new DAOException("University with such name has already been created");
        }
        University university = new University(name);
        universities.put(university.getName(), university);
        return university;
    }

    @Override
    public void delete(String name) throws DAOException {
        if(!checkExistence(name)) {
            throw new DAOException("There is no such university");
        }
        universities.remove(name);
    }

    @Override
    public void save(University university) throws DAOException {
        if(checkExistence(university.getName())){
            throw new DAOException("University with such name already exists");
        }

        universities.put(university.getName(), university);
    }

    @Override
    public University find(String name) throws DAOException {
        if(!checkExistence(name)){
            throw new DAOException("There is no such university");
        }
        return universities.get(name);

    }

    @Override
    public Collection<University> findAll() throws DAOException {
        if (universities.values().isEmpty()){
            throw new DAOException("You have no universities");
        }
        return universities.values();
    }
}
